<template>
  <div v-if="visible" class="dialog-overlay" @click="handleOverlayClick">
    <div class="dialog" @click.stop>
      <div class="dialog-header">
        <h2>创建房间</h2>
        <button class="close-btn" @click="$emit('close')">
          <span>&times;</span>
        </button>
      </div>
      
      <div class="dialog-content">
        <div class="form-container">
          <div class="form-group">
            <label for="roomName">房间名称 <span class="required">*</span></label>
            <input 
              id="roomName"
              v-model="form.roomName" 
              type="text" 
              placeholder="请输入房间名称"
              maxlength="20"
              :class="{ 'error': form.roomName && !form.roomName.trim() }"
            />
            <span v-if="form.roomName && !form.roomName.trim()" class="field-error">房间名称不能为空</span>
          </div>
          
          <!-- 玩家昵称由登录用户自动填充并隐藏输入 -->
          <input type="hidden" v-model="form.playerNickname" />
          
          <div class="form-group">
            <label for="maxPlayers">最大玩家数</label>
            <select id="maxPlayers" v-model="form.maxPlayers">
              <option value="2">2人</option>
              <option value="3">3人</option>
              <option value="4">4人</option>
              <option value="5">5人</option>
              <option value="6">6人</option>
            </select>
          </div>
          
          <div class="form-group">
            <label for="gameDuration">游戏时长（分钟）</label>
            <select id="gameDuration" v-model="form.gameDuration">
              <option value="1">1分钟</option>
              <option value="2">2分钟</option>
              <option value="3">3分钟</option>
              <option value="5">5分钟</option>
              <option value="10">10分钟</option>
            </select>
          </div>
          
          <button 
            class="submit-btn" 
            @click="handleCreateRoom"
            :disabled="!isFormValid || isCreating"
          >
            {{ isCreating ? '创建中...' : '创建房间' }}
          </button>
        </div>
      </div>
      
      <!-- 错误信息显示 -->
      <div v-if="errorMessage" class="error-message">
        {{ errorMessage }}
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRoomStore } from '@/stores/room'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

export default {
  name: 'CreateRoomDialog',
  props: {
    visible: { type: Boolean, default: false }
  },
  emits: ['close', 'room-created'],
  setup(props, { emit }) {
    const roomStore = useRoomStore()
    const isCreating = ref(false)
    const errorMessage = ref('')
    
    // 表单数据 - 更新字段名以匹配API
    const form = ref({ 
      roomName: '', 
      playerNickname: '', 
      maxPlayers: 5, 
      gameDuration: 2 
    })
    
    // 表单验证
    const isFormValid = computed(() => form.value.roomName.trim())
    
    // 处理创建房间
    const handleCreateRoom = async () => {
      if (!isFormValid.value) {
        ElMessage.warning('请填写完整的房间信息')
        return
      }
      
      // 检查用户是否已登录
      const userStore = useUserStore()
      if (!userStore.isAuthenticated) {
        ElMessage.warning('请先登录后再创建房间')
        // 可以在这里跳转到登录页面
        // router.push('/login')
        return
      }
      
      try {
        isCreating.value = true
        errorMessage.value = ''
        
        // 用登录用户名称自动填充昵称
        form.value.playerNickname = userStore.userDisplayName || userStore.user?.nickname || userStore.user?.username || '玩家'

        const response = await roomStore.createRoom({
          roomName: form.value.roomName.trim(),
          playerNickname: form.value.playerNickname.trim(),
          maxPlayers: parseInt(form.value.maxPlayers),
          gameDuration: parseInt(form.value.gameDuration)
        })
        
        console.log('创建房间API响应:', response)
        
        // 发送成功事件，包含用户填写的信息（在重置表单之前）
        const roomData = {
          ...response,
          roomId: response.data?.id || response.id || form.value.roomName,
          roomName: response.data?.roomName || response.roomName || form.value.roomName,
          playerNickname: form.value.playerNickname,
          maxPlayers: form.value.maxPlayers,
          gameDuration: form.value.gameDuration
        }
        
        emit('room-created', roomData)
        
        // 重置表单（在发送事件之后）
        form.value = {
          roomName: '',
          playerNickname: '',
          maxPlayers: 5,
          gameDuration: 2
        }
        
      } catch (error) {
        console.error('创建房间失败:', error)
        
        // 显示错误信息
        if (error.response?.status === 401) {
          errorMessage.value = '请先登录后再创建房间'
          ElMessage.error('请先登录后再创建房间')
        } else if (error.response?.data?.message) {
          errorMessage.value = error.response.data.message
          ElMessage.error(error.response.data.message)
        } else if (error.message) {
          errorMessage.value = error.message
          ElMessage.error(error.message)
        } else {
          errorMessage.value = '创建房间失败，请重试'
          ElMessage.error('创建房间失败，请重试')
        }
      } finally {
        isCreating.value = false
      }
    }
    
    // 处理遮罩层点击关闭
    const handleOverlayClick = () => { 
      emit('close')
      // 关闭时重置表单和错误信息
      form.value = {
        roomName: '',
        playerNickname: '',
        maxPlayers: 5,
        gameDuration: 2
      }
      errorMessage.value = ''
    }
    
    return { 
      form, 
      isCreating, 
      errorMessage, 
      isFormValid, 
      handleCreateRoom, 
      handleOverlayClick 
    }
  }
}
</script>

<style scoped>
.dialog-overlay { 
  position: fixed; 
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0; 
  background-color: rgba(0, 0, 0, 0.5); 
  display: flex; 
  align-items: center; 
  justify-content: center; 
  z-index: 1000; 
}

.dialog { 
  background: white; 
  border-radius: 12px; 
  box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04); 
  width: 90%; 
  max-width: 480px; 
  max-height: 90vh; 
  overflow-y: auto; 
}

.dialog-header { 
  display: flex; 
  justify-content: space-between; 
  align-items: center; 
  padding: 24px 24px 0 24px; 
  border-bottom: 1px solid #e5e7eb; 
  padding-bottom: 16px; 
}

.dialog-header h2 { 
  margin: 0; 
  font-size: 1.5rem; 
  font-weight: 600; 
  color: #111827; 
}

.close-btn { 
  background: none; 
  border: none; 
  font-size: 1.5rem; 
  cursor: pointer; 
  color: #6b7280; 
  padding: 4px; 
  border-radius: 4px; 
  transition: color 0.2s; 
}

.close-btn:hover { 
  color: #374151; 
}

.dialog-content { 
  padding: 24px; 
}

.form-container { 
  display: flex; 
  flex-direction: column; 
  gap: 20px; 
}

.form-group { 
  display: flex; 
  flex-direction: column; 
  gap: 8px; 
}

.form-group label { 
  font-weight: 500; 
  color: #374151; 
  font-size: 0.875rem; 
}

.form-group input, 
.form-group select { 
  padding: 12px 16px; 
  border: 1px solid #d1d5db; 
  border-radius: 8px; 
  font-size: 1rem; 
  transition: border-color 0.2s, box-shadow 0.2s; 
}

.form-group input:focus, 
.form-group select:focus { 
  outline: none; 
  border-color: #3b82f6; 
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); 
}

.form-group input.error {
  border-color: #dc2626;
}

.form-group input.error:focus {
  border-color: #dc2626;
  box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1);
}

.submit-btn { 
  padding: 12px 24px; 
  border: none; 
  border-radius: 8px; 
  font-size: 1rem; 
  font-weight: 500; 
  cursor: pointer; 
  transition: all 0.2s; 
  margin-top: 8px; 
  background-color: #3b82f6; 
  color: white; 
}

.submit-btn:hover:not(:disabled) { 
  background-color: #2563eb; 
  transform: translateY(-1px);
}

.submit-btn:disabled { 
  opacity: 0.6; 
  cursor: not-allowed; 
}

.error-message { 
  margin: 16px 24px 24px 24px; 
  padding: 12px 16px; 
  background-color: #fef2f2; 
  border: 1px solid #fecaca; 
  border-radius: 8px; 
  color: #dc2626; 
  font-size: 0.875rem; 
}

.field-error {
  color: #dc2626;
  font-size: 0.75rem;
  margin-top: 4px;
}

.required {
  color: #dc2626;
  margin-left: 4px;
}

@media (max-width: 640px) { 
  .dialog { 
    width: 95%; 
    margin: 20px; 
  } 
  
  .dialog-header, 
  .dialog-content { 
    padding: 16px; 
  } 
}
</style> 